package com.ruoyi.common.clients;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.clients.dto.CozeDTO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

@Component
public class CozeClient {
    private static final String API_URL = "https://api.coze.cn/open_api/v2/chat";
    // 设置连接超时时间为30秒
    private static final int CONNECT_TIMEOUT = 30000*100;
    // 设置读取超时时间为30秒
    private static final int READ_TIMEOUT = 30000*100;

    public static String sendRequest(String botId, String token, String query) {
        try {
            // 1. 创建连接
            URL url = new URL(API_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            // 2. 设置请求头
            conn.setRequestProperty("Authorization", "Bearer " + token);
            conn.setRequestProperty("Content-Type", "application/json");
            // 设置超时时间
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            
//            {
//                "bot_id": "%s",
//                    "user": "java_client_001",
//                    "query": "%s",
//                    "stream": false
//            }
            CozeDTO cozeDTO = new CozeDTO();
            cozeDTO.setBot_id(botId);
            cozeDTO.setUser("java_client_001");
            cozeDTO.setQuery(query);
            cozeDTO.setStream(false);

            // 3. 构建请求体
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonInput = objectMapper.writeValueAsString(cozeDTO);


//            String jsonInput = String.format();

            // 4. 发送请求
            conn.setDoOutput(true);
            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonInput.getBytes());
                os.flush();
            }

            // 5. 解析响应
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                StringBuilder response = new StringBuilder();
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                    }
                }
                return response.toString();
            } else {
                // 读取错误响应
                StringBuilder errorResponse = new StringBuilder();
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getErrorStream()))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        errorResponse.append(line);
                    }
                }
                System.err.println("Coze API请求失败，响应码: " + responseCode + ", 错误信息: " + errorResponse.toString());
            }
        } catch (Exception e) {
            System.err.println("Coze API请求异常: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String cotent=  sendRequest("7574488472707203126", "pat_j5W9fskaX0KzXJRzFOhVB7Xv152AEtgxstlm7UwfP3XW6o0Apitlm8d9COaCsw76", "我的测试结果 ESTJ ，测试原始值：{\"E\":12,\"I\":0,\"S\":12,\"N\":0,\"T\":12,\"F\":0,\"J\":12,\"P\":0}");

        return;
    }
}